package com.share.tool.m2d.kundb.tablestructure;


import com.share.common.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;


public class DbMainV2 {
    public static Map<String, Map<String, String>> dbMap = new HashMap<>();
    public static int ID_SPET = 0;

    public static void main(String[] args) {
        Db[] values = Db.values();
        for (Db item : values) {
            String name = item.getDbName();
            Map<String, String> map = dbMap.get(name);
            String filepath = item.getFilepath();
            if (new File(filepath).exists()) {
                System.out.println("正在处理文件=" + filepath);
                exe(filepath, map);
            } else {
                System.out.println("sql结构文件不存在-" + filepath);
            }
        }
    }


    static {
        //读取配置
        String productConfigurePath = DbMainV2.class.getClassLoader().getResource("kundb\\kundb.txt").getPath();
        List<String> list = FileUtil.readByLine(productConfigurePath);
        Map<String, String> map = null;
        boolean startFlag = false;
        for (String tmp : list) {
            String line = tmp.trim();
            if (line.length() == 0) {
                continue;
            }

            if (line.startsWith("[") && line.endsWith("]")) {
                map = new HashMap<>();
                dbMap.put(line, map);
                startFlag = true;
            } else {
                if (!startFlag) {/*没找到头部直接跳过*/
                    continue;
                }

                String[] split = line.split(",");
                if (split.length == 2) {
                    map.put(split[0].trim(), split[1].trim());
                } else if (split.length == 1) {
                    map.put(line, null);
                }
            }
        }

        if (startFlag == false) {
            System.err.println("配置异常");
        }
    }

    public static void exe(String tabelStructFile, Map<String, String> distrMap) {
        StringBuffer sb = new StringBuffer();
        List<String> midList = FileUtil.readByLine(tabelStructFile);
        List<String> list = filterHeader(midList);
        String tableName = null;
        TreeMap<Integer, String> keyMap = new TreeMap<>();
        for (String str : list) {
            String line = str.trim();
            if (line.length() == 0) {
//                sb.append("");
                continue;
            } else if (line.startsWith("--")) {
//                sb.append(line);
                continue;
            } else if (line.startsWith("/*")) {
//                sb.append("");
            } else if (line.startsWith("SET ")) {
//                sb.append("");
            } else if (line.startsWith("CREATE DATABASE")) {
//                sb.append("");
            } else if (line.startsWith("USE ")) {
//                sb.append("");
                continue;
            } else {
                if (line.startsWith("DROP")) {
                    tableName = null;
                    keyMap.clear();//用于分表key的提取
                    continue;
                } else if (line.startsWith("CREATE")) {
                    //获取表名字
                    tableName = line.replaceAll("CREATE", "").replaceAll("TABLE", "").replaceAll("IF", "").replaceAll("EXISTS", "").replaceAll(";", "").replaceAll("`", "").replaceAll("\\(", "").trim();

                    //删除语句
                    sb.append(System.lineSeparator());
                    sb.append("DROP TABLE IF EXISTS `" + tableName + "`;");
                    sb.append(System.lineSeparator());

                    //加建表语句
                    sb.append(line);
                    sb.append(System.lineSeparator());
                } else if (line.contains(")") && line.contains("ENGINE") && line.contains("=")) {
                    StringBuffer tmp = new StringBuffer(line);
                    tmp.deleteCharAt(tmp.length() - 1);

                    //有分表需求的才需要这个
                    if (distrMap.get(tableName) != null) {
                        tmp.append(" DISTRIBUTED BY HASH(" + (distrMap.get(tableName) != null ? distrMap.get(tableName) : keyMap.get(keyMap.keySet().toArray(new Integer[10])[0])) + ") USING `binary_md5`;");
                    }
                    //剔除默认编码-DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC
                    String vv = tmp.toString();
                    vv = vv.replace(" DEFAULT ", " ")
                            .replace(" ROW_FORMAT=DYNAMIC ", " ")
                            .replace(" CHARSET=utf8mb4 ", " ")
                            .replace(" CHARSET=utf8mb4", " ")
                            .replace(" CHARSET=utf8", " ")
                            .replace(" ROW_FORMAT=COMPACT ", " ")
                            .replace(" COLLATE=utf8_bin ", " ");

                    //自增id识别-AUTO_INCREMENT=429613
                    int a = vv.indexOf(" AUTO_INCREMENT");
                    if (a >= 0) {
                        try {
                            String au = vv.substring(a + 2);
                            String g1 = au.split(" ")[0];//原始值
                            String[] kv = g1.split("=");

                            String nstr = kv[0] + "=" + (Integer.parseInt(kv[1]) + ID_SPET) + " ";
                            vv = vv.replace(g1, nstr);
                        } catch (Exception e) {
                            System.out.println("数据异常table=" + tableName + ",line=" + vv);
                            throw new RuntimeException("数据异常" + tableName);
                        }
                    }


                    sb.append(vv);

                    if (!vv.endsWith(";")) {
                        sb.append(";");
                    }

                    sb.append(System.lineSeparator());
                } else {
                    //把非空内容加入进来
                    if (StringUtils.isNotBlank(line)) {

                        if (line.startsWith("`")) {
                            line = line.replace(" CHARACTER SET utf8 COLLATE utf8_bin ", " ");
                            line = line.replace(" COLLATE utf8_bin ", " ");
                        }
                        sb.append(line);
                        sb.append(System.lineSeparator());
                    }
                    keyMap.put(7, "session_id");
                }
            }
        }

        FileUtil.write(tabelStructFile + "-分表.txt", sb.toString());
    }

    private static List<String> filterHeader(List<String> list) {
        int i = 0;
        int flag = 0;
        List<String> relist = list;
        for (String str : list) {
            i++;
            String line = str.trim();
            if (line.equals("/*")) {
                flag = flag + 1;
            } else if (str.trim().equals("*/")) {
                flag = flag + 1;
                break;
            }

            if (line.startsWith("SET ")) {
                break;
            } else if (line.startsWith("DROP")) {
                break;
            } else if (line.startsWith("CREATE DATABASE")) {
                break;
            } else if (line.startsWith("USE ")) {
                break;
            }

            if (i > 20) {
                break;
            }
        }
        if (flag == 2) {
            relist = list.subList(i, list.size());
        }
        return relist;
    }
}

